const path = require("path");
const { app, BrowserWindow, ipcMain } = require("electron");
const qrImage = require("qr-image");
const DataManager = require("./DataManager");
const logger = require("./Logger").getLogger("err");
const Utils = require("./Utils");
const dateLimit = ["forever", "year", "halfyear", "season", "month", "week"];
const appName = app.name || app.getName();
const { argv } = require("process");
const appVersion = app.getVersion();
let Register = {
    Judge: function (openMainWindow) {
        if (appName === "test" || argv[2] === 'test') {
            return openMainWindow();
        }
        Register.openMainWindow = openMainWindow;
        Utils.readRegInfo()
            .then((info) => {
                if (!info.right) {
                    Unregistered();
                } else {
                    verifyCode(info)
                        .then(function () {
                            openMainWindow();
                        })
                        .catch(function (err) {
                            logger.error("verifyCode", err);
                            Unregistered();
                        });
                }
            })
            .catch((err) => {
                logger.error("readRegInfo", err);
                Unregistered();
            });
    },
};

function Unregistered() {
    const { screen } = require("electron");
    var time = Date.now();
    const { width, height } = screen.getPrimaryDisplay().bounds;
    let win = new BrowserWindow({
        width: width,
        height: height,
        minWidth: width,
        minHeight: height,
        maxWidth: width,
        maxHeight: height,
        fullscreen: true,
        frame: false,
        alwaysOnTop: true,
        webPreferences: {
            preload: path.join(__dirname, "./Font"),
        },
    });

    win.loadURL(path.join(__dirname, "../app_pages/register/register.html"));
    win.show();

    ipcMain.on("req-qr-image", function () {
        if (__dirname.indexOf("locales") === -1 && false) {
            win.webContents.send("cuowu", "软件封装加密方式错误");
        } else {
            Utils.getMachineId(appName)
                .then(function (info) {
                    var obj = {
                        aId: appName,
                        d: info.dId,
                        c: info.cpu,
                        ds: info.memery,
                        t: time,
                        m: info.mac,
                        sv: appVersion,
                        dd: info.serialId,
                        os: info.osVersion,
                    };

                    Utils.cipherText(JSON.stringify(obj))
                        .then((result) => {
                            var qrContent =
                                DataManager.getActiveUrl() + "?" + result;
                            let stream = qrImage.image(qrContent, {
                                ec_level: "M",
                            }); //设置容错率level为30%
                            var chunks = [];
                            stream.on("data", function (chunk) {
                                chunks.push(chunk);
                            });

                            stream.on("end", function () {
                                var result = Buffer.concat(chunks);
                                win.webContents.send(
                                    "qrimage",
                                    result.toString("base64")
                                );
                            });
                        })
                        .catch((err) => {
                            logger.error("cipherText", err);
                            win.webContents.send("cuowu", err);
                        });
                })
                .catch(function (err) {
                    logger.error("getMachineId", err);
                    win.webContents.send("cuowu", err.toString());
                });
        }
    });
    ipcMain.on("winClose", () => {
        win.hide();
        setTimeout(function () {
            app.quit();
        }, 100);
    });
    ipcMain.on("register", function (e, code) {
        verifyCode({ code: code.trim(), time })
            .then(function (compiledCode) {
                Register.openMainWindow();
                Utils.writeRegInfo(compiledCode, time, 1);
                win.close();
            })
            .catch(function (err) {
                logger.error("verifyCode", err);
                win.webContents.send("cuowu", err.toString());
            });
    });
}

function verifyCode(info) {
    return Utils.getMachineId(appName)
        .then(function (deviceInfo) {
            return Promise.all(
                dateLimit.map((item) => {
                    return Utils.cipherWithCode(
                        deviceInfo.dId + info.time + item
                    );
                })
            );
        })
        .then(function (resultArr) {
            return new Promise(function (resolve, reject) {
                if (info.code.length < 8) {
                    reject("注册码输入错误，请检查重新输入...");
                } else {
                    var index = resultArr.findIndex((item) => {
                        return item
                            .toUpperCase()
                            .startsWith(info.code.toUpperCase());
                    });

                    if (index != -1) {
                        if (
                            (dateLimit[index] == "year" &&
                                Date.now() - info.time >
                                365 * 24 * 60 * 60 * 1000) ||
                            (dateLimit[index] == "halfyear" &&
                                Date.now() - info.time >
                                182 * 24 * 60 * 60 * 1000) ||
                            (dateLimit[index] == "season" &&
                                Date.now() - info.time >
                                90 * 24 * 60 * 60 * 1000) ||
                            (dateLimit[index] == "month" &&
                                Date.now() - info.time >
                                30 * 24 * 60 * 60 * 1000) ||
                            (dateLimit[index] == "week" &&
                                Date.now() - info.time >
                                7 * 24 * 60 * 60 * 1000)
                        ) {
                            Utils.writeRegInfoExpire();
                            reject("验证已经过期");
                        } else {
                            resolve(resultArr[index]);
                        }
                    } else {
                        reject("注册码输入错误，请检查重新输入...");
                    }
                }
            });
        });
}

module.exports = Register;
